URL = r"http://download.savannah.nongnu.org/releases/openexr/openexr-%(VERSION)s.tar.gz"
DEFAULT_VERSION = "2.1.0"
VERSIONS = ["2.1.0"]
DEPENDS = ["zlib", "ilmbase"]

#note: copy step makes a deploy folder by adding ilm base to the openexr libs and include,
#todo add this step also for the linux builder

from source.builders import CMakeBuilder, ConfigureMakeBuilder
import os, shutil, sys

class OpenExrConfigureMakeBuilder( ConfigureMakeBuilder ):
  """ subclass of ConfigureMakeBuilder with custom configure step """
  def configureparameters(self):
    params = ["--disable-ilmbasetest"]
    params.append("--with-ilmbase-prefix="+self.dependencies["ilmbase"].installpath())
    zlibincludedir = self.dependencies["zlib"].getincludedir()
    zliblibdir = self.dependencies["zlib"].getlibdir()
    env = os.environ
    env['CPPFLAGS'] = "-I"+zlibincludedir
    env['LDFLAGS'] = "-L"+zliblibdir
    return params

class OpenExrBuilder( CMakeBuilder ):
  """ subclass of CMakeBuilder with custom configure step """

  def configure(self):
    """upgrade the files and build the solution """
    if self.machine.platform == 'Windows':
      # Add CMake find module FindIlmBase.cmake
      # Clean up previous content
      if os.path.exists(self.extractedpath + "\\CMakeModules"):
        shutil.rmtree(self.extractedpath + "\\CMakeModules")
      os.mkdir(self.extractedpath + "/CMakeModules")
      shutil.copyfile(sys.path[0] + "/library/additions/openexr/CMakeModules/FindIlmBase.cmake", self.extractedpath + "\\CMakeModules\\FindIlmBase.cmake")

      # Add new directory CMakeModules to CMake module path
      replacements = []
      replacements.append(( "PROJECT (openexr)", "\nSET(CMAKE_MODULE_PATH\n  ${CMAKE_CURRENT_SOURCE_DIR}/CMakeModules\n  ${CMAKE_MODULE_PATH}\n)\n"))
      self.replaceInFile( self.extractedpath + "\\CMakeLists.txt", replacements )

      # Patch CMakeLists.txt in order to invoke the FindIlmBase.cmake
      replacements = []
      replacements.append(( "FIND_PACKAGE(ZLIB REQUIRED)", "FIND_PACKAGE(IlmBase REQUIRED)\nFIND_PACKAGE(ZLIB REQUIRED)"))
      self.replaceInFile( self.extractedpath + "\\CMakeLists.txt", replacements )

      # Patch IlmImf/CMakeLists.txt to use the derived ILMBASE_LIBRARIES for the targets b44ExpLogTable and IlmImf
      replacements = []
      replacements.append(( "  Half", "  ${ILMBASE_LIBRARIES}"))
      replacements.append(( "  Iex-2_1", ""))
      replacements.append(( "  Imath-2_1", ""))
      replacements.append(( "  IlmThread-2_1", ""))
      self.replaceInFile( self.extractedpath + "\\IlmImf\\CMakeLists.txt", replacements )
      
      replacements = []
      replacements.append(( "#include <assert.h>", "#include <assert.h>\n#include <cctype>"))
      self.replaceInFile( self.extractedpath + "\\exrmultipart\\exrmultipart.cpp", replacements )

      replacements = []
      replacements.append(("ChannelList channelsInView \(const std::string &viewName,", "IMF_EXPORT\nChannelList channelsInView (const std::string &viewName,"))
      self.replaceLinesInFile( self.extractedpath+"\\IlmImf\\ImfMultiView.h", replacements )

    zlibdep = self.dependencies["zlib"]
    ilmbasedep = self.dependencies["ilmbase"]
    incdir = " -DZLIB_INCLUDE_DIR="+zlibdep.getincludedir()
    lib = " -DZLIB_LIBRARY="+zlibdep.getlibdir()+os.sep+{ "Linux" : "libz.so ", "Windows" : "zlib.lib " }[self.machine.platform]
    ilmbase = " -DILMBASE_PACKAGE_PREFIX="+ilmbasedep.targetpath()
    debug_postfix = ' -DCMAKE_DEBUG_POSTFIX="d" '
    CMakeBuilder.configure(self, incdir+lib+ilmbase+debug_postfix)

  def copy(self):
    ilmbasedep = self.dependencies["ilmbase"]
    print ilmbasedep.getincludedir(), self.getincludedir()    
    self.copydir( ilmbasedep.getincludedir()+os.sep+"OpenEXR", self.getincludedir()+os.sep+"OpenEXR")
    self.copydir( ilmbasedep.getlibdir(), self.getlibdir())


def decider( machine, dirs ):
  return { "Linux" : OpenExrConfigureMakeBuilder,
           "Windows" : OpenExrBuilder }[machine.platform]

BUILDER = decider

